<?php

namespace Api\Controller;

use Think\Controller;
use Think\Log;
use Think\Hook;
/**
 * 公共控制器
 * @author
 * 后缀带_iframe的ACTION是在iframe中加载的，用于统一返回格式
 */
class CommonController extends Controller {

    private $data;
    private $error;

    function _initialize() {
//        Log::write($_POST['paramer'], Log::INFO);
        $paramer = json_decode(htmlspecialchars_decode(I('request.paramer')), true);
        $this->data = $paramer['data'];
        $this->analyse($paramer);
    }

    function analyse($paramer) {
        $platform = $paramer['platform'];
        $udid = $paramer['udid'];
        $version = $paramer['version'];
        $analyse = "请求设备类型：" . $platform . '，唯一设备标识：' . $udid . '，请求app版本：' . $version;
        //Log::write($analyse, Log::INFO);
        if (empty($platform) || (strtolower($platform) != "android" && strtolower($platform) != "ios")) {
            $this->errorReturn("未知设备类型错误");
        } else if (empty($version)) {
            $this->errorReturn("未知应用版本错误");
        } else if (empty($udid)) {
            $this->errorReturn("未知设备标识错误");
        } else {
            //记录到数据库
            Log::write($analyse, Log::INFO);
        }
    }

    function getData() {
        return $this->data;
    }

    function successReturn($msg = '操作成功', $data = array(), $result = true) {
        if ($result) {
            if (empty($data)) {
                $data = array();
            }
//          Log::write(var_export($data, true), Log::INFO);
            $this->ajaxReturn(array('status' => '1', 'msg' => $msg, 'data' => $data));
        } else {
            $this->ajaxReturn(array('status' => '1', 'msg' => $msg));
        }
    }

    function errorReturn($error) {
        $this->ajaxReturn(array('status' => '0', 'msg' => $error));
    }

    function validate($_validate) {
        if ($_validate && !empty($_validate[0])) {
            foreach ($_validate as $value) {
                if (!isset($this->data[$value[0]])) {
                    $this->error = $value[1];
                    return false;
                }
            }
        } else {
            if (!isset($this->data[$_validate[0]])) {
                $this->error = $_validate[1];
                return false;
            }
        }
        return true;
    }

    function getError() {
        return $this->error;
    }

    function unsetNullValue($dataArr) {
        foreach ($dataArr as $key => $value) {
            if (empty($value) && $value != 0) {
                unset($dataArr[$key]);
            } else if (is_array($value)) {
                $dataArr[$key] = $this->unsetNullValue($value);
            }
        }
        return $dataArr;
    }

}
